package com.example.demojdbcmysql.config;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: kai.yang
 * @Date: 2019-10-25 14:18
 */


public class UserLogTableShardingAlgorithm implements PreciseShardingAlgorithm<Timestamp> {


    private static final String TblUserLogName = "auth_user_log";

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Timestamp> preciseShardingValue) {
        String tb_name = TblUserLogName;

        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(preciseShardingValue.getValue().getTime());
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        if (UserLogTableRangeShardingAlgorithm.dbConfig.keySet().contains(year)) {
            if (month >= 1 && month <= 3) {
                tb_name = TblUserLogName + "_" + year + "01";
            }
            if (month >= 4 && month <= 6) {
                tb_name = TblUserLogName + "_" + year + "02";
            }
            if (month >= 7 && month <= 9) {
                tb_name = TblUserLogName + "_" + year + "03";
            }
            if (month >= 10 && month <= 12) {
                tb_name = TblUserLogName + "_" + year + "04";
            }
        }

        for (String each : collection) {
            if (each.equals(tb_name)) {
                return each;
            }
        }

        throw new IllegalArgumentException();

    }


}
